package im.agents.contextmanager;

import im.agents.utility.Utility;
import im.domain.Context;
import im.domain.XMLSerializer;
import jade.core.Agent;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.proto.AchieveREResponder;

/**
 * @author Silvia
 * Behaviour implementato da tutti quegli agenti che su rihiesta devono poter infomare circa
 * il contesto del nodo a cui appartengono (attualmente Requester e ServiceProvider)
 *
 */
public class GetAgentContextResponder extends AchieveREResponder {
	
	Context context;

	public GetAgentContextResponder(Agent myAgent) {
		super(myAgent, AchieveREResponder.createMessageTemplate(FIPANames.InteractionProtocol.FIPA_REQUEST));
		// TODO Auto-generated constructor stub
	}
	
	/* (non-Javadoc)
	 * @see jade.proto.AchieveREResponder#prepareResultNotification(jade.lang.acl.ACLMessage, jade.lang.acl.ACLMessage)
	 */
	protected ACLMessage prepareResultNotification(ACLMessage request,ACLMessage response){
		findActualContext();
		ACLMessage informMsg = request.createReply();
		informMsg.setPerformative(ACLMessage.INFORM);
		informMsg.setContent(XMLSerializer.doSerialize(context));
		//System.out.println("INFORMO SUL CONTEXT");
		return informMsg;
	}

	private void findActualContext() {
		//System.out.println("sono il getagentcontextresponder e appartengo a"+myAgent.getName());
		DFAgentDescription context_ds = null;
		context_ds = Utility.findAgent(myAgent,"context-info");
		if(context_ds== null)
			System.out.println("Nessun CM trovato");
		else{
			String convId = Utility.createConvId(myAgent);
			ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
			request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
			request.setSender(myAgent.getAID());
			request.addReceiver(context_ds.getName());
			request.setConversationId(convId);
			myAgent.send(request);

			boolean gotIt=false;
			while(!gotIt){
				ACLMessage response = myAgent.receive(
				MessageTemplate.MatchConversationId(convId));
				if(response!=null){
					context = (Context) XMLSerializer.doDeserialize(response.getContent());
				    gotIt = true;
				}
				else{
					block();
				}
			}		
		}
	}
	protected ACLMessage prepareResponse(ACLMessage request){
		return null;
	}
	
}


